﻿$(function () {
    $("#user-grid").datagrid({
        url: $.Api("Sys/User/Grid"),
        nowrap: false, rownumbers: true, border: false,
        fit: true, singleSelect: true,
        pageSize: 20, pagination: true,
        idField: "ID", toolbar: "#user-tools",
        sortName: "InsertTime", sortOrder: "asc",
        columns:
        [[
            { field: "UserName", title: "账号", width: 120, align: "center", sortable: true },
            { field: "Name", title: "姓名", width: 80, align: "center", sortable: true },
            { field: "Mobile", title: "手机", width: 100, align: "center", sortable: true },
            { field: "Tel", title: "电话", width: 100, align: "center", sortable: true },
            { field: "Email", title: "邮箱", width: 140, align: "center", sortable: true },
            { field: "InsertTime", title: "注册时间", width: 140, align: "center", sortable: true },
            {
                field: "IsSuper", title: "超人", width: 50, align: "center", sortable: true,
                formatter: function (value, row, index) { return $.GetYesOrNo(value); }
            },
            {
                field: "IsVisible", title: "启用", width: 50, align: "center", sortable: true,
                formatter: function (value, row, index) { return $.GetYesOrNo(value); }
            }
            
        ]]
    });

    $("#user-department-tree").tree({
        lines: true, url: $.Api("Sys/Department/FilterTree"),
        onSelect: function (node) {
            $("#user-grid").datagrid("clearChecked");
            $("#user-grid").datagrid("load", { departmentid: node.id });
        }
    });

    $("#user-searchbox").searchbox({
        width: 150, prompt: "请输入用户姓名查询",
        searcher: function (value) {
            $("#user-grid").datagrid("clearChecked");
            $("#user-grid").datagrid("load", { search: value });
        }
    });
});

var User = {
    //添加
    Insert: function () {
        var node = $("#user-department-tree").tree("getSelected");
        if (node) {
            User.Mutual("添加", "sys/user/Edit.aspx?did=" + node.id);
        }
        else { User.Mutual("添加", "sys/user/Edit.aspx"); }
    },
    //修改
    Update: function () {
        var row = $("#user-grid").datagrid("getSelected");
        if (row) {
            User.Mutual("修改", "sys/user/Edit.aspx?id=" + row.ID);
        }
        else { $.EasyuiSlide(nullrowmsg); }
    },
    //删除
    Delete: function () {
        var row = $("#user-grid").datagrid("getSelected");
        if (row) {
            $.EasyuiConfirm("确认删除?", function (del) {
                if (del) {
                    $.AjaxMask({
                        url: $.Api("Sys/User/Delete"),
                        type: "post", data: { id: row.ID },
                        success: function (result) {
                            result = JSON.parse(result);
                            $.EasyuiSlide(result.Message);
                            if (result.Success) { User.Reload(); }
                        }
                    });
                }
            });
        }
        else { $.EasyuiSlide(delnullrowmsg); }
    },
    //实体操作
    Mutual: function (title, href) {
        $.ModelDialog({
            title: title, href: href, width: 260,
            handler: function () {
                $.ModelForm({
                    validate: true, button: $(this),
                    id: "#user-model",
                    url: $.Api("Sys/User/Save"),
                    success: function (result) { User.Reload(); }
                });
            },
            onLoad: function () { User.FormInit(); }
        });
    },
    //弹窗初始化
    FormInit: function () {
        $("#user-departmentid").combotree({
            width: 150, panelHeight: "auto",
            url: $.Api("Sys/Department/Tree")
        });
        if ($("#user-userid").val()) {
            $("#user-username").attr("disabled", "disabled");
            $("tr").remove("#user-password-row");
        }
    },

    //启用
    Enable: function () {
        User.EnableOrDisable(true);
    },
    //禁用
    Disable: function () {
        User.EnableOrDisable(false);
    },
    //启用禁用
    EnableOrDisable: function (bool) {
        var row = $("#user-grid").datagrid("getSelected");
        if (row) {
            $.AjaxMask({
                url: $.Api("Sys/User/EnableOrDisable"),
                type: "post", data: { id: row.ID, bit: bool },
                success: function (result) {
                    result = JSON.parse(result);
                    $.EasyuiSlide(result.Message);
                    if (result.Success) { User.Reload(); }
                }
            });
        }
        else { $.EasyuiSlide(nullrowmsg); }
    },

    //刷新列表
    Reload: function () {
        $.DataGridReload("#user-grid");
    },

    //重置密码
    Reset: function () {
        var row = $("#user-grid").datagrid("getSelected");
        if (row) {
            $.ModelDialog({
                title: "重置密码", width: 260,
                href: "sys/user/SetPwd.aspx?id=" + row.ID,
                handler: function () {
                    $.ModelForm({
                        validate: true, button: $(this),
                        id: "#user-setpwd",
                        url: $.Api("Sys/User/SetPwd"),
                        success: function (result) { }
                    });
                },
                onLoad: function () { }
            });
        }
        else { $.EasyuiSlide(nullrowmsg); }
    },

    //展开部门
    DepTreeRedo: function () {
        $("#user-department-tree").tree("expandAll");
    },
    //收起部门
    DepTreeUndo: function () {
        $("#user-department-tree").tree("collapseAll");
    },
    //查看全部
    DepAll: function () {
        var node = $("#user-department-tree").tree("getRoot");
        $("#user-department-tree").tree("select", node.target);
        $("#user-grid").datagrid("clearChecked");
        $("#user-grid").datagrid("load", { departmentid: node.id });
    },

    //导出表格
    Export: function () {
        location.href = $.Api("Sys/User/Export"); return false;
    },

    //分配角色
    Assign: function () {
        var row = $("#user-grid").datagrid("getSelected");
        if (row) {
            $.ModelDialog({
                title: "分配角色", width: 420, height: 380,
                href: "sys/user/Assign.aspx",
                handler: function () {
                    var rows = $("#assign-userrole-grid").datagrid("getRows");
                    var data = []; var button = $(this);
                    for (var i = 0; i < rows.length; i++) { data.push(rows[i].RoleID); }
                    $.AjaxMask({
                        url: $.Api("Sys/User/Assign"), type: "post",
                        data: { id: row.ID, data: data.join(",") },
                        success: function (result) {
                            result = JSON.parse(result);
                            if (result.Success) {
                                $.ButtonCloseDialog(button);
                                $.EasyuiSlide(result.Message);
                            }
                            else { $.EasyuiMsg(result.Message); }
                        }
                    });
                },
                onLoad: function () { User.AssignInit(row.ID); }
            });
        }
        else { $.EasyuiSlide(nullrowmsg); }
    },
    //分配初始化
    AssignInit: function (id) {
        var macolumns = [[
            {
                field: "Name", title: "名称", width: 134, align: "center",
                formatter: function (v, r, i) {
                    if (v) { return v; } else { return r.SysRole.Name }
                }
            }
        ]];
        $("#assign-role-grid").datagrid({
            url: $.Api("Sys/Role/AllGrid"),
            title: "全部角色", nowrap: false, rownumbers: true,
            idField: "ID", fit: true, singleSelect: true,
            columns: macolumns, onDblClickCell: User.AssignAdded
        });
        $("#assign-userrole-grid").datagrid({
            url: $.Api("Sys/User/RoleGrid"),
            queryParams: { id: id },
            title: "已选角色", nowrap: false, rownumbers: true,
            idField: "ID", fit: true, singleSelect: true,
            columns: macolumns, onDblClickCell: User.AssignRemove
        });
        $("#assign-userrole-userid").val(id);
    },
    //移除角色
    AssignRemove: function () {
        var row = $("#assign-userrole-grid").datagrid("getSelected");
        if (row) {
            var index = $("#assign-userrole-grid").datagrid("getRowIndex", row);
            $("#assign-userrole-grid").datagrid("deleteRow", index);
        }
        else { $.EasyuiSlide(nullrowmsg); }
    },
    //加入角色
    AssignAdded: function () {
        var row = $("#assign-role-grid").datagrid("getSelected");
        if (row) {
            var rows = $("#assign-userrole-grid").datagrid("getRows");
            for (var i = 0; i < rows.length; i++) {
                if (row.ID == rows[i].RoleID) { return false; }
            }
            $("#assign-userrole-grid").datagrid("appendRow", {
                UserID: $("#assign-userrole-userid").val(),
                RoleID: row.ID, Name: row.Name
            });
        }
        else { $.EasyuiSlide(nullrowmsg); }
    },

    //分配权限
    Purview: function () {
        var row = $("#user-grid").datagrid("getSelected");
        if (row) {
            $.ModelDialog({
                title: "分配权限",
                href: "sys/user/Purview.aspx",
                toolbar: User.PurviewTool(),
                width: $(window).width() - 20,
                height: $(window).height() - 20,
                handler: function () {
                    var button = $(this);
                    $.AjaxMask({
                        url: $.Api("Sys/User/Purview"), type: "post",
                        data: { id: row.ID, data: User.PurviewData() },
                        success: function (result) {
                            result = JSON.parse(result);
                            if (result.Success) {
                                $.ButtonCloseDialog(button);
                                $.EasyuiSlide(result.Message);
                            }
                            else { $.EasyuiMsg(result.Message); }
                        }
                    });
                },
                onLoad: function () { User.PurviewInit(row.ID); }
            });
        }
        else { $.EasyuiSlide(nullrowmsg); }
    },
    //获取结果
    PurviewData: function () {
        var nodes = $("input:checked[edit='yes']", $("#user-purview-panel"));
        var data = [];
        for (var i = 0; i < nodes.length; i++) {
            data.push($(nodes[i]).attr("mbid"));
        }
        return data.join(",");
    },
    //分配权限工具栏
    PurviewTool: function () {
        return [{
            text: "全选", iconCls: 'icon-add', handler: function () {
                var nodes = $("input[edit='yes']", $("#user-purview-panel")).not("input:checked");
                for (var i = 0; i < nodes.length; i++) {
                    $(nodes[i]).prop("checked", true);
                }
            }
        }, {
            text: "取消", iconCls: 'icon-remove', handler: function () {
                var nodes = $("input:checked[edit='yes']", $("#user-purview-panel"));
                for (var i = 0; i < nodes.length; i++) {
                    $(nodes[i]).prop("checked", false);
                }
            }
        }, {
            text: "折叠", iconCls: 'icon-undo', handler: function () {
                $.TreeGridCollapseAll("#user-purview-grid");
            }
        }, {
            text: "展开", iconCls: 'icon-redo', handler: function () {
                $.TreeGridExpandAll("#user-purview-grid");
            }
        }];
    },
    //分配权限初始化
    PurviewInit: function (id) {
        $.AjaxMask({
            url: $.Api("Sys/Button/AllGrid"), type: "get",
            success: function (result) {
                var columns = []; result = JSON.parse(result);
                for (var i = 0; i < result.length; i++) {
                    columns.push({
                        field: result[i].Function, title: result[i].Name,
                        width: 60, align: "center",
                        formatter: function (value, row, index) {
                            return User.PurviewFormatter(value);
                        }
                    });
                }
                User.PurviewGrid(id, columns);
            }
        });
    },
    //获取权限表
    PurviewGrid: function (id, columns) {
        $("#user-purview-grid").treegrid({
            url: $.Api("Sys/Menu/UserPurviewGrid"),
            queryParams: { id: id }, title: "功能导航",
            nowrap: false, rownumbers: true, fit: true,
            singleSelect: true, treeField: "Name",
            idField: "ID", parentField: "Parent",
            frozenColumns: [[
                { field: "Name", title: "名称", width: 200, align: "left" }
            ]],
            columns: [columns]
        });
    },
    //获取勾选框
    PurviewFormatter: function (node) {
        if (node.disabled == "true") { return "-"; }

        if (node.value == "true") {
            return "<input edit='yes' mbid='" + node.mbid + "' type='checkbox' checked='checked' />";
        }
        else {
            return "<input edit='yes' mbid='" + node.mbid + "' type='checkbox' />";
        }
    }
};